package server

import (
	pb "go-kit-service/api/video"
	"go-kit-service/pkg/config"
	"go-kit-service/pkg/endpoint"
	"go-kit-service/pkg/logger"
	"go-kit-service/pkg/service"
	"go-kit-service/pkg/transport"
	"net"

	"go.uber.org/zap"
	"google.golang.org/grpc"
)

type VideoServer struct {
	service *service.VideoService
}

func NewServer() *VideoServer {
	return &VideoServer{
		service: service.NewService(),
	}
}

func (server *VideoServer) Run() {
	endpoints := endpoint.MakeEndpoints(server.service)

	grpcServer(endpoints)
}

func grpcServer(endpoints endpoint.Endpoints) {
	addr := config.C.Service.GRPCAddr

	GRPCListen, err := net.Listen("tcp", addr)
	if err != nil {
		logger.Error("grpc listen tcp ", zap.String("error", err.Error()), zap.String("addr", addr))
		return
	}

	baseServer := grpc.NewServer()
	GRPCServer := transport.NewGRPCServer(endpoints)

	pb.RegisterVideoServer(baseServer, GRPCServer)
	logger.Info("grpc server start", zap.String("addr", addr))
	if err := baseServer.Serve(GRPCListen); err != nil {
		logger.Error("grpc server run ", zap.String("error", err.Error()), zap.String("addr", addr))
	}
}
